//
//  SeatsListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/11/13.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"

#import "SeatsListNaviView.h"
#import "SeatsListBottomView.h"

#import "SearchKeyWordItemCell.h"

#import "SeatsListHeaderReusableView.h"
#import "SeatsListFooterReusableView.h"



#import "EditSeatsViewController.h"
#import "PreviewSeatsViewController.h"

#import "SeatsListViewController.h"

@interface SeatsListViewController ()<ZZLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) SeatsListNaviView *searchNavi;

@property (nonatomic, strong) SeatsListBottomView *bottomView;

/**页面主视图*/
@property (nonatomic , strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray <CommonSeatsModel *>*dataArray;
//进入控制器时间
@property(nonatomic,strong)NSString *inTime;
@end

@implementation SeatsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    self.inTime = [NSString stringWithFormat:@"%0.0f",[Utilities getCurrentTimestamp]];
}
- (void)dealloc
{
    NSLog(@"SeatsListViewController ---dealloc");
    [[StatisticManager shareManager]insertBrowseUserActiveQuantityWithToolType:@"4" WithInTime:self.inTime];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self request_seats];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [self request_seats];
    return YES;
}

- (void)initView {
    
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    self.rt_disableInteractivePop = NO;
    
    self.view.backgroundColor = UIColorHex(0xf8f8f8);

    [self.view addSubview:self.searchNavi];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.collectionView];

    [self.searchNavi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(kStatusBarHeight+NavBar_Height+50);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(60+Bottom_SafeHeight);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(15);
//        make.right.mas_equalTo(-15);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(self.searchNavi.mas_bottom);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
    }];
    
    [self initViewAction];
    
    [self.collectionView reloadData];
}

- (void)initViewAction {
    
    WEAKSELF
    self.bottomView.SeatsListBottomBlock = ^(SeatsListBottomActionType type) {
    
        switch (type) {
            case SeatsListBottomActionType_add:{
                //添加
//                EditSeatsViewController *vc = [[EditSeatsViewController alloc] init];
//                vc.title = @"主桌";
//                [weakSelf.navigationController pushViewController:vc animated:YES];
                [weakSelf request_Addseats];
                
            } break;
            case SeatsListBottomActionType_preview:{
                //预览
                PreviewSeatsViewController *vc = [[PreviewSeatsViewController alloc] init];
                vc.title = @"预览";
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            case SeatsListBottomActionType_handle:{
            
                [weakSelf shareAction];
                //分享
            } break;
            default:
                break;
        }
    };
}

- (void)shareAction {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?userName=%@&nickName=%@",BA_GlobalH5_Domain,@"/weddingSeats",[TTUserModel sharedObject].username,[Utilities stringToUnicode:[TTUserModel sharedObject].nickname]];
    model.title = [NSString stringWithFormat:@"%@婚宴席位表",[TTUserModel sharedObject].nickname];
    model.content = @"已为您安排好席位，请查看您的席位表，欢迎您的到来";
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark- 协议方法
//collectionView的协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchKeyWordItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchKeyWordItemCellID" forIndexPath:indexPath];
    cell.itemTitleLab.text = self.dataArray[indexPath.section].userSeatList[indexPath.row].name;
    cell.itemTitleLab.backgroundColor = UIColorHex(0xffffff);
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray[section].userSeatList.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头

    WEAKSELF
    if (kind == UICollectionElementKindSectionHeader) {
        SeatsListHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SeatsListHeaderReusableView" forIndexPath:indexPath];
        
//        if ([self.dataArray[indexPath.section].isMainTable isEqualToString:@"1"]) {
//            headerView.seatsTitleLab.text = @"主桌";
//        } else {
//
//            if (self.dataArray[indexPath.section].seatsName.length > 0) {
                headerView.seatsTitleLab.text = self.dataArray[indexPath.section].seatsName;
//            } else {
//                headerView.seatsTitleLab.text = [NSString stringWithFormat:@"%ld桌",(long)indexPath.section];
//            }
//        }
        
        headerView.seatsCountLab.text = [NSString stringWithFormat:@"%@/%@座位已安排",self.dataArray[indexPath.section].number,self.dataArray[indexPath.section].seatsNumber];

        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        SeatsListFooterReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SeatsListFooterReusableView" forIndexPath:indexPath];
        
        footerView.SeatsListFooterBlock = ^{
          
            EditSeatsViewController *vc = [[EditSeatsViewController alloc] init];
            
            if (weakSelf.dataArray[indexPath.section].seatsName.length > 0) {
                vc.title = weakSelf.dataArray[indexPath.section].seatsName;
            } else {
                vc.title = [NSString stringWithFormat:@"%ld桌",(long)indexPath.section];
            }
            
//            vc.wsId = weakSelf.dataArray[indexPath.section].wsId;
            vc.model = weakSelf.dataArray[indexPath.section];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
        reusableView = footerView;
    }
    return reusableView;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的度
    return 30;//同一section下请不要改变高度.
}

- (CGFloat)layout:(ZZLayout *)layout widthForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的宽

    return self.dataArray[indexPath.section].userSeatList[indexPath.row].itemWidth;//这里可以根据内容传入任意宽度
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距
    return 5;
}

- (CGFloat) layout:(ZZLayout *)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距
    return 5;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度
    return CGSizeMake(TTScreenWidth, 86);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾部的高度
    return CGSizeMake(TTScreenWidth, 60);
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {
    return [UIColor whiteColor];
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeAutomateFloat delegate:self];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth, self.view.bounds.size.height - kStatusBarHeight - NavBar_Height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColorHex(0xf8f8f8);
        
        //注册cell
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchKeyWordItemCell" bundle:nil] forCellWithReuseIdentifier:@"SearchKeyWordItemCellID"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SeatsListHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SeatsListHeaderReusableView"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SeatsListFooterReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SeatsListFooterReusableView"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }        
    }
    return _collectionView;
}

- (NSMutableArray<CommonSeatsModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (SeatsListNaviView *)searchNavi {
    if (!_searchNavi) {
        _searchNavi = [[NSBundle mainBundle] loadNibNamed:@"SeatsListNaviView"owner:nil options:nil].firstObject;
        [_searchNavi.cancleBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        _searchNavi.searchTF.delegate = self;
    }
    return _searchNavi;
}

- (SeatsListBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"SeatsListBottomView"owner:nil options:nil].firstObject;

    }
    return _bottomView;
}

- (void)request_seats {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.searchNavi.searchTF.text forKey:@"name"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MarrySeatsPage];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSArray *list = [data valueForKey:@"data"];
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *dic = list[i];
                        CommonSeatsModel *model = [CommonSeatsModel modelWithDictionary:dic];
                        
                        model.userSeatList = @[].mutableCopy;
                        NSArray *userSeatList = [dic valueForKey:@"userSeatList"];
                        if ([userSeatList isKindOfClass:[NSArray class]]) {
                            
                            for (int j = 0; j < userSeatList.count; j++) {
                                NSDictionary *seatDic = userSeatList[j];
                                
                                CommonUserSeatsModel *seatModel = [CommonUserSeatsModel modelWithDictionary:seatDic];
                                seatModel.itemWidth = [Utilities getStringWidthWithString:seatModel.name fontSize:14 andHeight:30];
                                [model.userSeatList addObject:seatModel];
                            }
                        }
                        [weakSelf.dataArray addObject:model];
                    }
                }
                [weakSelf.collectionView reloadData];

            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
    
}

- (void)request_Addseats {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_AddSeats];
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在请求加桌子"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            [weakSelf request_seats];
            [SVProgressHUD showSuccessWithStatus:@"添加成功"];
            [SVProgressHUD dismissWithDelay:1];
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
